<template>

  <div style="position: relative;min-width: 1000px;">
    <Card shadow>
      <!-- <div @click="refresh" class="p-absolute refresh-btn">
        <Icon size='24' type="md-refresh" />
      </div> -->
      <div style="position: absolute;right: 16px; top: 16px;z-index: 10;">

        <Select v-model="searchObj.sotre_id" style="width:200px; margin-right: 10px;" placeholder='请选择门店'
          @on-change="selectStore">
          <Option v-for="item in data.storeList" :value="item.id" :key="item.id">{{ item.name }}</Option>
        </Select>
        <DatePicker @on-change="changeDate" type="date" placeholder="请选择时间" style="width: 110px">
        </DatePicker>
      </div>

      <Tabs value="name1" v-model="tabsName" @on-click="hoverTab">
        <TabPane :label="item.name" :name="'name'+item.id" v-for="(item,index) in data.venueList">
          <Table :columns="data.columns" border :data="data.list" :loading="loading">
            <template slot-scope="{ row, column,index }" slot="btn">

              <!--  <Button class="btn" disabled   >停止预约{{row[column.key]}}</Button> -->
              <Button class="btn" disabled v-if="row[column.key]=='stop'">停止预约</Button>
              <Checkbox v-else-if="row[column.key]!='stop' && row[column.key]==0" class="btn"
                v-model="checkboxArr[column.key+row.hour]" :true-value="1" :false-value="0"
                @on-change="changeTime($event,row.hour,column.key)" size="large">空闲</Checkbox>

              <Button v-else-if="row[column.key]!='stop' && row[column.key]==1" class="btn" type="success" ghost
                @click="makeDetail(row[column.key+'_order_id'])">已预约</Button>
            </template>
          </Table>
          <!--  <Row>
            <Col class="head-col" span="1" v-for="(item,index) in data.headColumn">{{item}}{{index!=0?'号场':''}}</Col>
          </Row>
          <Row v-for="item in data.timeColumn">
            <Col class="head-col" span="1">{{item}}:00-{{item+1}}:00 </Col>
            <Col class="head-col" style="background-color: #FFFFFF; cursor: pointer;" span="1" v-for="(item,index) in 6">
              <Button class="btn" @click="createOrder">可预约</Button>
            </Col>
          </Row> -->

        </TabPane>

      </Tabs>


    </Card>

    <!-- 查看预约订单详情弹窗 -->
    <!-- @on-ok="ok" @on-cancel="cancel" -->
    <Modal v-model="detailModal" title="订单详情" width='60%'>
      <div class="detail-table">
        <div class="base-info">
          <Row class='row-main-title font16 table-head-bg padding10'>
            <Col span="24">基本信息</Col>
          </Row>
          <Row class='row-main-content'>
            <Col span="8"><span class="font-gray">订单号：</span>{{formItem.detail.order_no}}</Col>
            <Col span="8"><span class="font-gray">交易流水号：</span>{{formItem.detail.callback_trade_no}}</Col>
            <Col span="8"><span class="font-gray">订单状态：</span><label
              style="color: #ff6600;">{{formItem.detail.order_estate_name}}</label></Col>
          </Row>
          <Row class='row-main-content'>
            <Col span="8"><span class="font-gray">门店：</span>{{formItem.detail.store_name}}</Col>
            <Col span="8"><span class="font-gray">类目：</span>{{formItem.detail.venue_name}} -
            {{formItem.detail.number}}号场</Col>
            <Col span="8"><span class="font-gray">预约时间：</span>{{formItem.detail.make_time_range}}</Col>
          </Row>
          <Row class='row-main-content'>
            <Col span="8"><span
              class="font-gray">姓名：</span>{{formItem.detail.username}}({{formItem.detail.vip_level_name}})</Col>
            <Col span="8"><span class="font-gray">电话：</span>{{formItem.detail.mobile}}</Col>
            <Col span="8"><span class="font-gray">预约时长：</span>{{formItem.detail.hour}}</Col>
          </Row>
          <Row class='row-main-content'>
            <Col span="8"><span class="font-gray">支付金额：</span>￥{{formItem.detail.amount}}元
            <span v-if="formItem.detail.coupon_id>0">({{formItem.detail.coupon_name}}
              -{{formItem.detail.coupon_fee}}元)</span>
            </Col>
            <Col span="8"><span class="font-gray">支付方式：</span>{{formItem.detail.pay_type_name}}</Col>
            <Col span="8"><span class="font-gray">支付时间：</span>{{formItem.detail.pay_time}}</Col>
          </Row>
          <Row class='row-main-content'>
            <Col span="8"><span class="font-gray">渠道类型：</span>{{formItem.detail.channel==1?'小程序':'手工单'}}</Col>
            <Col span="8"><span class="font-gray">下单时间：</span>{{formItem.detail.create_time}}</Col>
            <Col span="8"><span class="font-gray">取消时间：</span>{{formItem.detail.cancel_time}}</Col>
          </Row>
        </div>

      </div>
      <div slot="footer">
        <Button @click='detailModal=false'>关闭</Button>

      </div>
    </Modal>

    <!-- 创建订单弹窗-->
    <Modal v-model="createModal" title="添加订单" width='700'>


      <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="80">
        <FormItem label="门店" style="margin-bottom: 0px;">
          {{changeStore.name}}
        </FormItem>
        <FormItem label="运动项目" style="margin-bottom: 0px;">
          {{venue_name}}
        </FormItem>
        <FormItem label="场地" style="margin-bottom: 0px;">
          {{curNumber.join(",")}}号场地
        </FormItem>
        <FormItem label="时间" style="margin-bottom: 0px;">
          {{make_date}} &nbsp&nbsp(共{{curHourRange.length}}小时)
        </FormItem>
        <FormItem label="费用">
          ￥<span style="font-size: 22px; color: red;">{{formValidate.amount}}</span>元&nbsp;&nbsp;
          <span v-if="data.venueAmount.length>0"
            v-for="item in data.venueAmount">({{item.time_range}}&nbsp&nbsp{{item.amount}}元/小时)&nbsp;&nbsp;</span>
        </FormItem>

        <FormItem label="用户姓名" prop="username">
          <Input v-model="formValidate.username" style="width:300px;" placeholder="请输入用户姓名"></Input>
          <Button type="warning" @click='getUserData'>选择会员</Button>
        </FormItem>
        <FormItem label="联系方式" prop="mobile">
          <Input v-model="formValidate.mobile" placeholder="请输入联系方式"></Input>
        </FormItem>


        <FormItem label="支付方式" prop="type">
          <RadioGroup v-model="formValidate.type">
            <Radio :label="item.value" v-for="(item,index) in type">{{item.name}}{{item.value==2?'('+formValidate.balance+'元)':''}}</Radio>&nbsp;&nbsp;&nbsp;&nbsp;

          </RadioGroup>
        </FormItem>


      </Form>
      <div slot="footer">
        <Button @click='createModal=false'>取消</Button>
        <Button type="primary" @click='create_order("formValidate")'>确定</Button>
      </div>
    </Modal>

    <!-- 选择会员弹窗 -->
    <Modal v-model="changeUserModal" title="选择会员" width='800'>
      <div class="p-relative" style="padding-top: 10px;">

        <div class="flex-box search-area">

          <div class="flex-item">
            <Input v-model="searchObj.keywords" placeholder="请输入姓名或手机号" style="width: 150px" />
          </div>
          <div class="flex-item search-btn" @click="searchUser">
            <Button type="warning">搜索</Button>
          </div>
          <div class="flex-item search-btn" @click="resetUser">
            <Button>重置</Button>
          </div>

        </div>
      </div>
      <Table :columns="tableOption" :data="data.userList" border :no-data-text="loadingText ? loadingText : '暂无数据'"
        border ref="tables" editable search-place="top">

        <template slot-scope="{ row, index }" slot="username">
          {{row.username==''?row.nickname:row.username}}
        </template>
        <template slot-scope="{ row, index }" slot="action">
          <div class="flex-box flex-center flex-margin">

            <Button type='warning' @click="confirmChange(row, index)" size='small'>选择</Button>

          </div>
        </template>
      </Table>
      <Page class="foot-page" :current='page.current' :total="page.total" :page-size="page.pageSize" show-total
        show-elevator @on-change="changepage"></Page>
        <div slot="footer">
          <Button @click='changeUserModal=false'>取消</Button>

        </div>
    </Modal>
    <Button type="warning" style="position: fixed; right: 50px; bottom: 100px;" @click="createOrder">添加订单</Button>
  </div>

</template>
<script>
  import {
    getList,
    createOrder,
    getDetail,
    getUserData

  } from '@/api/home/job.js'


  export default {
    name: 'home',
    components: {


    },
    data() {
      return {
        loadingText: '',
        tabsName: '',
        detailModal: false,
        changeUserModal: false,
        checkboxArr: {},
        loading: true,
        timeArr: [],
        createModal: false,
        searchObj: {
          sotre_id: 0
        },
        type: [{
            name: '微信',
            value: '1'
          },
          {
            name: '支付宝',
            value: '3'
          },
          {
            name: '现金',
            value: '4'
          },
          // {
          //   name: '运动卡余额',
          //   value: '2'
          // }
        ],
        data: {
          columns: [],
          venueList: [],
          list: [],
          storeList: [], //门店数据
          numberList: [], //场地编号
          classItem: {
            price: 15
          },
          venueAmount: [],
          userList: []
        },

        changeStore: {},
        formItem: {
          detail: []
        },
        formValidate: {
          username: '',
          mobile: '',
          type: '',
          amount: 0,
          balance:0,
          user_id:0
        },
        ruleValidate: {
          username: [{
            required: true,
            message: '请输入用户名称',
            trigger: 'blur'
          }],
          mobile: [{
            required: true,
            message: '请输入用户联系方式',
            trigger: 'blur'
          }],
          type: [{
            required: true,
            message: '请输入支付方式',
            trigger: 'change'
          }],


        },
        detailModal: false,
        cardDetailModal: false,
        store_id: '', //选中的门店id,
        curDate: '', //当前选中日期,
        curHourRange: [], //当前选中的小时段
        curNumber: [], //当前选择的场地号
        make_date: '',
        order_id: 0,
        class_id: 0,
        venue_name: '',
        tableOption: [{
            title: 'ID',
            key: 'id',
            align: 'center',
            width: '80'
          },
          {
            title: '会员名称',
            key: 'username',
            align: 'center',
            slot: 'username',
          },
          {
            title: '会员名称',
            key: 'mobile',
            align: 'center',

          },
          // {
          //   title: '运动卡余额',
          //   key: 'balance',
          //   align: 'center'
          // },
          {
            title: '会员等级',
            key: 'vip_level',
            align: 'center',
            render: (h, params) => {
              let txt = '';
              switch (params.row.vip_level) {
                case 0:
                  txt = '大众会员'
                  break;
                case 1:
                  txt = '一星会员'
                  break;
                case 2:
                  txt = '二星会员'
                  break;
                case 3:
                  txt = '三星会员'
                  break;
                case 4:
                  txt = '四星会员'
                  break;
                case 5:
                  txt = '五星会员'
                  break;
              }

              return h('span', txt)
            }
          },

          {
            title: '操作',
            slot: 'action',
            align: 'center'

          }
        ],
        page: {
          pageSize: 8,
          current: 1,
          total: 0
        },

      }
    },
    mounted() {
      let _this = this;
    },
    created() {
      let date = new Date()
      let year = date.getFullYear()
      let month = date.getMonth() + 1
      let day = date.getDate()
      //组装今天日期
      this.curDate = year + '-' + month.toString().padStart(2, 0) + '-' + day.toString().padStart(2, 0);

      this.getList();
    },
    methods: {


      getList() {
        let _this = this;

        let params = {
          class_id: this.class_id,
          store_id: this.store_id,
          change_date: this.curDate
        }
        getList(params).then(res => {
          if (res.data.status == 1) {
            _this.data.columns = res.data.data.head_colmun
            _this.data.list = res.data.data.list
            _this.data.storeList = res.data.data.storeList
            _this.data.venueAmount = res.data.data.venueAmount
            _this.data.venueList = res.data.data.venueList
            if (_this.store_id == 0) {
              _this.changeStore = _this.data.storeList[0]
              _this.store_id = _this.changeStore.id
              _this.searchObj.sotre_id = _this.changeStore.id

            }

            _this.loading = false
            if (_this.tabsName == '') {
              _this.tabsName = 'name' + _this.data.venueList[0].id
              _this.venue_name = _this.data.venueList[0].name
              _this.class_id = _this.data.venueList[0].id
            }


          }
        }).catch(function(error) {
          // 异常
          console.log(error)
        })

      },

      changeDate(e) {
        this.curDate = e;
        this.getList();

      },
      changeTime(e, hour, number) {
        let _this = this
        //当前勾选的场地号和之前勾选的场地号不一致则清空从新来
        number = number.substr(6); //截取场地号
        // if (this.curNumber != number) {
        //   this.curHourRange = [];
        //   for (var i in this.checkboxArr) {
        //     this.checkboxArr[i] = 0;
        //   }
        // }

        var key = 'number' + number + hour;
        this.checkboxArr[key] = 1

        if (this.curHourRange.length > 0) {
          let last_hour = this.curHourRange[this.curHourRange.length - 1]; //获取最后的时间段
          //向后跨时间段处理
          if (hour > last_hour) {
            if (hour - last_hour > 1) {
              this.checkboxArr[key] = 0;
              this.$Message.error('不可跨时间段预约!')
              return;
            }
          } else {

            if (this.curHourRange[0] - hour > 1) {
              this.checkboxArr[key] = 0;
              this.$Message.error('不可跨时间段预约!')
              return;
            }
          }
        }

        //选中则追加时段
        if (e) {
          if (this.curHourRange.indexOf(hour) < 0) {
            this.curHourRange.push(hour)
          }
        } else {
          //取消则删除时段
          var index = this.curHourRange.indexOf(hour);
          if (index > -1) {
            this.curHourRange.splice(index, 1);

          }

        }


        let venueAmount = this.data.venueAmount
        _this.formValidate.amount = 0;

        //循环勾选的时间段去计算不同时间段的费用总计curHourRange
        this.curHourRange.forEach((hour) => {
          venueAmount.forEach((item) => {
            if (hour >= item.hour[0] && hour <= item.hour[1]) {
              _this.formValidate.amount += parseFloat(item.amount);

            }
          })

        })

        if(this.curNumber.indexOf(number)<0){
           this.curNumber.push(number) //记录场地号
           // this.$forceUpdate()
        }

        _this.formValidate.amount = _this.formValidate.amount*this.curNumber.length;

        this.curHourRange.sort(function(a, b) {
          return a - b
        });

      },
      //手动创建订单
      createOrder() {

        if (this.curHourRange.length <= 0) {
          this.$Message.error('请勾选要预约的空闲场地时段!')
          return;
        }

        //按顺序排序
        this.curHourRange.sort(function(a, b) {
          return a - b
        });

        if (this.curHourRange.length == 1) {
          this.make_date = this.curDate + ' ' + this.curHourRange[0] + ':00 - ' + (this.curHourRange[0] + 1) + ':00'

        } else {
          this.make_date = this.curDate + ' ' + this.curHourRange[0] + ':00 - ' + (this.curHourRange[this.curHourRange
            .length - 1] + 1) + ':00'
        }

        this.createModal = true;

      },
      selectStore(e) {

        this.store_id = e;
        this.searchObj.store_id = e;
        this.loading = true
        this.tabsName = ''
        this.data.storeList.forEach((item) => {
          if (item.id == e) {
            this.changeStore = item;
            return false;
          }
        })

        this.getList()
      },
      refresh() {

        this.getList()
      },
      //订单提交
      create_order(name) {
        let _this = this;

        this.$refs[name].validate((valid) => {

          if (valid) {

            let params = {
              username: _this.formValidate.username,
              mobile: _this.formValidate.mobile,
              pay_type: _this.formValidate.type,
              store_id: _this.changeStore.id,
              store_name: _this.changeStore.name,
              address: _this.changeStore.address,
              venue_name: _this.venue_name,
              venue_class_id: _this.class_id,
              make_date: _this.curDate,
              make_time_range: _this.curHourRange,
              number: _this.curNumber,
              amount: _this.formValidate.amount,
              user_id: _this.formValidate.user_id,
            }

            createOrder(params).then(res => {

              if (res.data.status == 1) {
                _this.createModal = false;
                _this.checkboxArr = {}
                _this.curHourRange = [],
                _this.curNumber = []
                _this.formValidate.username = ''
                _this.formValidate.mobile = ''
                _this.formValidate.balance = 0
                _this.formValidate.user_id = 0
                _this.formValidate.type = ''
                _this.getList();
                _this.$Message.success('操作成功')
              }
            }).catch(function(error) {
              // 异常
              console.log(error)
            })
          } else {
            this.$Message.error('请输入必填项!')
          }
        })

      },
      makeDetail(id) {

        this.order_id = id
        this.detailModal = true
        this.view(id)
      },
      view(id) {
        let _this = this
        let params = {
          id: id
        }
        getDetail(params).then(res => {
          if (res.data.status == 1) {
            let result = res.data.data
            _this.formItem.detail = result.detail

          } else {
            let config = {
              content: res.data.message,
              background: true
            }
            _this.$Message.error(config)
          }
        }).catch(function(error) {
          // 异常
          console.log(error)
        })
      },
      hoverTab(name) {
        // console.log(334,this.checkboxArr )
        for (var i in this.checkboxArr) {
          this.checkboxArr[i] = 0;
        }
        this.loading = true;
        this.tabsName = name;
        this.curNumber = [];
        this.make_date = '';
        this.curHourRange = [];
        this.formValidate = {}
        // this.checkboxArr = {}
        this.class_id = name.substr(4) //截取场地类id

        let temp = this.data.venueList;
        for (var i in temp) {
          if (temp[i].id == this.class_id) {
            this.venue_name = temp[i].name

          }
        }
        // console.log(11,this.venue_name)
        this.getList();
      },
      getUserData(){
        this.changeUserModal = true;
        let _this = this


        let params = {
          page: this.page.current,
          keywords: _this.searchObj.keywords
        }

        getUserData(params).then(res => {
          if (res.data.status == 1) {
            let result = res.data.data
            _this.data.userList = result.list
            _this.page.total = result.total
            _this.page.pageSize = result.size
          }
        }).catch(function(error) {
          // 异常

        })
      },
      changepage(e){
        this.page.current = e;
        this.getUserData();
      },
      searchUser(){
        this.getUserData();
      },
      resetUser(){
        this.searchObj = {
           keywords:''
        }
        this.getUserData();
      },
      confirmChange(item){
         this.formValidate.username = item.username==''?item.nickname:item.username
         this.formValidate.mobile = item.mobile
         this.formValidate.balance = item.balance
         this.formValidate.user_id = item.id
         this.changeUserModal = false
      }
    }

  }
</script>

<style lang="scss">
  @import "./job";
</style>
